﻿
using System;
using System.Globalization;

using Irony.Compiler;

using Microsoft.Scripting.Runtime;

namespace IronLua.Ast {

	public class LiteralExpression : Expression {

		readonly object value;

		public object Value {
			get { return value; }
		}

		public override LuaNodeType NodeType {
			get { return LuaNodeType.LiteralExpression; }
		}

		public LiteralExpression (CompilerContext context, NonTerminal nonTerminal, SourceLocation location, AstNodeList childNodes)
			: base (context, nonTerminal, location, childNodes)
		{
			value = GetValue ();
		}

		object GetValue ()
		{
			var token = ChildNodes[0] as Token;
			var val = token.Value;
			switch (token.Element.Name) {
			case "true":
				return RuntimeHelpers.True;
			case "false":
				return RuntimeHelpers.False;
			case "nil":
				return null;
			case "Number":
				return double.Parse (token.Text, NumberFormatInfo.InvariantInfo);
			case "DblQString":
			case "SQString":
				return val;
			}

			throw new NotSupportedException (token.Element.Name);
		}

		public override void Accept (ILuaAstVisitor visitor)
		{
			visitor.VisitLiteralExpression (this);
		}
	}
}
